<!DOCTYPE html>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>

<div id="comboBox"
    role="combobox"
    aria-autocomplete="list"
    aria-expanded="true"
    aria-haspopup="listbox">
  <input id="comboBoxInput"
      type="text"
      aria-controls="states-list"
      aria-activedescendant="state2">
</div>

<ul id="stateList"
    role="listbox">
  <li id="state1" role="option">Alabama</li>
  <li id="state2" role="option">Alaska</li>
</ul>

<script>
  setup(() => {
    window.comboBoxInput = accessibilityController.accessibleElementById('comboBoxInput');
    document.querySelector('input').focus();
  });

  test(() => {
    assert_true(window.comboBoxInput.isFocused, 'Combo box should be focused.');
    let state1 = accessibilityController.accessibleElementById('state1');
    assert_false(state1.isSelected, 'State1 should not be selected.');
    assert_true(state1.isFocusable, 'State1 should be focusable.');
    assert_false(state1.isFocused, 'State1 should not be focused.');

    let state2 = accessibilityController.accessibleElementById('state2');
    assert_equals(window.comboBoxInput.activeDescendant, state2, 'State2 should be the active descendant.');
    assert_true(state2.isSelected, 'State2 should be selected.');
    assert_true(state2.isFocusable, 'State2 should be focusable.');
    assert_false(state2.isFocused, 'State2 should not be focused.');
  }, 'An option with an activedescendant pointing to it is selected.');

  test(() => {
    document.querySelector('input').setAttribute('aria-activedescendant', 'state1');

    assert_true(window.comboBoxInput.isFocused, 'Combo box should be focused.');
    let state1 = accessibilityController.accessibleElementById('state1');
    assert_equals(window.comboBoxInput.activeDescendant, state1, 'State1 should be the active descendant.');
    assert_true(state1.isSelected, 'State1 should be selected.');
    assert_true(state1.isFocusable, 'State1 should be focusable.');
    assert_false(state1.isFocused, 'State1 should not be focused.');

    let state2 = accessibilityController.accessibleElementById('state2');
    assert_false(state2.isSelected, 'State2 should not be selected.');
    assert_true(state2.isFocusable, 'State2 should be focusable.');
    assert_false(state2.isFocused, 'State2 should not be focused.');

    document.querySelector('input').setAttribute('aria-activedescendant', 'state2');
  }, 'Changing the activedescendant should change the item that is selected.');
</script>
